//
//  SkyDriveMediaShareCommunity.m
//  MediaShareBB
//
//  Created by Artak Gevorgyan on 5/23/13.
//  Copyright (c) 2013 InnoriseEntertainment. All rights reserved.
//

#import "SkyDriveMediaShareCommunity.h"
#import "AppDelegate.h"
#import "MediaShareBBUtilityMethods.h"
#import "MediaShareData.h"

@interface SkyDriveMediaShareCommunity() {
	NSString* _clientId;
    NSString* _userName;
    NSString* _uploadedFileLink;
	LiveConnectClient* _liveClient;
	BOOL _isUploading;
	BOOL _isGettingSharedLink;
	NSString* _uploadedFileId;
	MediaShareData* _sharedMediaData;
    BOOL _isSuccesfullyUploaded;
}

@end

@implementation SkyDriveMediaShareCommunity

-(id) init {
	self = [super init];
	if (self) {
		super.name = @"SkyDrive";
		super.communityType = MEDIA_SHARE_COMMUNITY_SKY_DRIVE;
		super.supportedMediaTypes = [[NSArray alloc] initWithObjects:
									 [NSNumber numberWithInt:IMAGE_MEDIA_TYPE],
									 [NSNumber numberWithInt:VIDEO_MEDIA_TYPE],
									 [NSNumber numberWithInt:URL_MEDIA_TYPE], nil];
	}
	return self;
}

// Superclass method
-(NSString*) description {
	NSString* d = @"SkyDrive description";
	return d;
}

// Superclass method
-(void) configureWithCredentials:(NSDictionary*) credentials {
	_clientId = [credentials valueForKey:@"clientId"];
}

// Superclass method
-(void) login {
    NSString* str = [[NSUserDefaults standardUserDefaults] valueForKey:@"Login"];
    if([str isEqualToString:@"signin"]){
		_liveClient = [[LiveConnectClient alloc] initWithClientId:_clientId delegate:self];
//		[_liveClient getWithPath:@"me/skydrive/files" delegate:self userState:@"get"];
        [_liveClient getWithPath:@"me" delegate:self userState:@"me"];
    } else {
        if(!_liveClient){
            _liveClient = [[LiveConnectClient alloc] initWithClientId:_clientId
															   scopes:[NSArray arrayWithObjects:@"wl.signin,wl.skydrive", nil]
															 delegate:self
															userState:@"initialize"];
        }
    }
}

//Superclass method
-(void) loginWithAnotherUser {
    [_liveClient logoutWithDelegate:self
                                userState:@"initialize"];
}

//Superclass method
-(NSString*) getUserName {
    return _userName;
}

//Superclass method
-(NSString*) sharedMediaLink {
    return _uploadedFileLink;
}

// Superclass method
-(void) shareMedia:(MediaShareData*) data {
	if ([super isValidMediaType:data.mediaType]) {
		_sharedMediaData = data;
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(willSharingMedia:through:)]) {
			[super.delegate willSharingMedia:_sharedMediaData
									 through:self];
		}
		if (IMAGE_MEDIA_TYPE == data.mediaType) {
			[self shareImage];
		} else if (VIDEO_MEDIA_TYPE == data.mediaType) {
			[self shareVideo];
		}

	} else {
		NSLog(@"%s: Unsupported media type:%d", __PRETTY_FUNCTION__, data.mediaType);
	}
}

#pragma mark - LiveAuthDelegate methods

-(void) authCompleted: (LiveConnectSessionStatus) status
              session: (LiveConnectSession*) session
            userState: (id) userState {

    if ([userState isEqual:@"initialize"]) {
        [[NSUserDefaults standardUserDefaults] setValue:@"init" forKey:@"Login"];
        [[NSUserDefaults standardUserDefaults] synchronize];
		AppDelegate* app = [UIApplication sharedApplication].delegate;

        [_liveClient login:app.window.rootViewController
					scopes:[NSArray arrayWithObjects:@"wl.signin,wl.skydrive,wl.photos,wl.skydrive_update", nil]
				  delegate:self
				 userState:@"signin"];
    }
    if ([userState isEqual:@"signin"]) {
        [[NSUserDefaults standardUserDefaults] setValue:@"signin" forKey:@"Login"];
        [[NSUserDefaults standardUserDefaults] synchronize];
//        [_liveClient getWithPath:@"me/skydrive/files"
//						delegate:self
//					   userState:@"get"];
        [_liveClient getWithPath:@"me" delegate:self userState:@"me"];
    }
}

-(void) authFailed:(NSError*) error userState:(id) userState {
    NSLog(@"%s: Failed with error: %@", __PRETTY_FUNCTION__, error);
	_liveClient = nil;
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(loginFailedWithError:)]) {
		[super.delegate loginFailedWithError:error];
	}
}

#pragma mark - LiveOperationDelegate methods

-(void) liveOperationSucceeded:(LiveOperation*) operation {
	NSLog(@"%s: liveOperationSucceeded", __PRETTY_FUNCTION__);
    if ([operation.userState isEqual:@"me"]) {
        NSLog(@"Operation ------- %@", [operation.result objectForKey:@"name"]);
        _userName = [operation.result objectForKey:@"name"];
    }
	if (!_isUploading && !_isGettingSharedLink) {
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(loginSuccess)]) {
			[super.delegate loginSuccess];
		}
	} else if (_isUploading) {
		NSLog(@"%s: Succesfully uploaded", __PRETTY_FUNCTION__);
		_isUploading = NO;
		_uploadedFileId = [operation.result objectForKey:@"id"];
		[self getLinkToFile];
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(didFinishSharingMedia:through:)]) {
            _isSuccesfullyUploaded = YES;
//			[super.delegate didFinishSharingMedia:_sharedMediaData
//										  through:self];
		}
	} else if (_isGettingSharedLink) {
		_isGettingSharedLink = NO;
		NSLog(@"%s: Public link of uploaded file: %@", __PRETTY_FUNCTION__,
													[operation.result objectForKey:@"link"]);
        _uploadedFileLink = [operation.result objectForKey:@"link"];
        if (_isSuccesfullyUploaded) {
            _isSuccesfullyUploaded = NO;
            [super.delegate didFinishSharingMedia:_sharedMediaData
                                          through:self];
        }
	}
}

-(void) liveOperationFailed:(NSError*) error
                  operation:(LiveOperation*) operation {
	NSLog(@"%s: liveOperationFailed with error: %@", __PRETTY_FUNCTION__, error);
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(didFailedSharingMedia:through:withError:)]) {
		[super.delegate didFailedSharingMedia:_sharedMediaData
									  through:self
									withError:error];
	}
}

#pragma mark - Private methods

-(void) shareImage {
	_isUploading = YES;
	NSString* name = [NSString stringWithFormat:@"%@.png", _sharedMediaData.fileName];
	[_liveClient uploadToPath:@"me/skydrive"
					 fileName:name
						 data:_sharedMediaData.data
					 delegate:self];
}

-(void) shareVideo {
    _isUploading = YES;
    NSString* s = [NSString stringWithFormat:@"%@", _sharedMediaData.path];
    NSData* fileToUpload = [[NSData alloc]initWithContentsOfFile:s];
	NSString* name = [NSString stringWithFormat:@"%@.mp4", _sharedMediaData.fileName];
    [_liveClient uploadToPath:@"me/skydrive"
                     fileName:name
                         data:fileToUpload
                     delegate:self];
}

-(void) getLinkToFile {
	NSString* s = [NSString stringWithFormat:@"%@%@", _uploadedFileId, @"/shared_read_link"];
	_isGettingSharedLink = YES;
	[_liveClient getWithPath:s
					delegate:self
				   userState:@"onClickGetLinkToFileButton"];
}

@end
